package pkg

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

// Client struct holds the necessary parameters for connecting to Aliyun SMS service.
type Client struct {
	AccessKeyID     string
	AccessKeySecret string
	RegionID        string
	SignName        string
	TemplateCode    string
}

// NewClient creates a new instance of the SMS client.
func NewClient(accessKeyID, accessKeySecret, regionID, signName, templateCode string) *Client {
	return &Client{
		AccessKeyID:     accessKeyID,
		AccessKeySecret: accessKeySecret,
		RegionID:        regionID,
		SignName:        signName,
		TemplateCode:    templateCode,
	}
}

// SendSMS sends an SMS message using Aliyun SMS service.
func (c *Client) SendSMS(phoneNumber string, code string) error {
	client, err := dysmsapi.NewClientWithAccessKey(c.RegionID, c.AccessKeyID, c.AccessKeySecret)
	if err != nil {
		return fmt.Errorf("failed to create Aliyun SMS client: %v", err)
	}
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["PhoneNumbers"] = phoneNumber // For simplicity, assuming only one phone number
	request.QueryParams["SignName"] = c.SignName
	request.QueryParams["TemplateCode"] = c.TemplateCode
	request.QueryParams["TemplateParam"] = "{\"code\":" + code + "}"
	response, err := client.ProcessCommonRequest(request)
	if response.IsSuccess() {
		return nil
	} else {
		return fmt.Errorf("failed to send SMS: %v", err)
	}
}
